// pages/profile/favorites/favorites.js
const api = require('../../../utils/api.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    favoritesList: [],
    loading: true,
    hasMore: true,
    page: 1,
    size: 20,
    total: 0,
    
    // 筛选条件
    activeTab: 0,
    tabs: [
      { name: '全部', type: 'all' },
      { name: '用户作品', type: 'user_work' },
      { name: '示例图', type: 'example' },
      { name: '图片', type: 'image' }
    ],
    
    // 删除模式
    deleteMode: false,
    selectedIds: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadFavorites();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 每次显示页面时刷新数据
    this.refreshFavorites();
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.refreshFavorites().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreFavorites();
    }
  },

  /**
   * 刷新收藏列表
   */
  async refreshFavorites() {
    this.setData({
      favoritesList: [],
      page: 1,
      hasMore: true,
      loading: true
    });
    await this.loadFavorites();
  },

  /**
   * 加载收藏列表
   */
  async loadFavorites() {
    try {
      this.setData({ loading: true });
      
      const params = {
        page: this.data.page,
        size: this.data.size
      };
      
      // 如果有筛选条件
      const currentTab = this.data.tabs[this.data.activeTab];
      if (currentTab.type !== 'all') {
        params.type = currentTab.type;
      }
      
      const response = await api.getUserFavorites(params);
      console.log('收藏列表请求参数:', params);
      console.log('收藏列表响应:', response);
      console.log('响应数据类型:', typeof response.data);
      console.log('响应数据内容:', response.data);
      console.log('响应分页信息:', {
        total: response.total,
        pages: response.pages,
        current: response.current,
        size: response.size,
        hasPrevious: response.hasPrevious,
        hasNext: response.hasNext
      });
      console.log('响应成功标志:', response.success);
      console.log('响应状态码:', response.code);
      console.log('响应消息:', response.message);
      
      // 检查响应是否成功
      if (response.success || response.code === 200) {
        // 处理嵌套的响应结构
        let actualData = response.data;
        
        // 如果response.data是一个包含data字段的对象，则使用内层的data
        if (actualData && typeof actualData === 'object' && actualData.data && Array.isArray(actualData.data)) {
          console.log('检测到嵌套响应结构，使用内层数据');
          const records = actualData.data || [];
          const total = actualData.total || 0;
          const current = actualData.current || this.data.page;
          const size = actualData.size || this.data.size;
          
          console.log('从嵌套结构提取的数据:', { records, total, current, size });
          
          // 处理数据...
          this.handleFavoritesData(records, total, current, size);
        } else if (Array.isArray(actualData)) {
          console.log('检测到直接数组响应结构');
          const records = actualData;
          const total = response.total || 0;
          const current = response.current || this.data.page;
          const size = response.size || this.data.size;
          
          // 处理数据...
          this.handleFavoritesData(records, total, current, size);
        } else {
          console.warn('未知的响应数据结构:', actualData);
          this.setData({
            favoritesList: [],
            total: 0,
            hasMore: false,
            loading: false
          });
        }
      } else {
        throw new Error(response.message || '加载收藏失败');
      }
    } catch (error) {
      console.error('加载收藏失败:', error);
      console.error('错误详情:', {
        message: error.message,
        stack: error.stack,
        name: error.name
      });
      
      let errorMessage = '加载失败';
      if (error.message) {
        if (error.message.includes('map')) {
          errorMessage = '数据格式错误，请稍后重试';
        } else if (error.message.includes('network') || error.message.includes('timeout')) {
          errorMessage = '网络连接失败，请检查网络';
        } else {
          errorMessage = error.message;
        }
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none'
      });
      
      this.setData({ 
        loading: false,
        favoritesList: [],
        total: 0,
        hasMore: false
      });
    }
  },

  /**
   * 处理收藏数据
   */
  handleFavoritesData(records, total, current, size) {
    // 确保records是数组
    if (!Array.isArray(records)) {
      console.warn('收藏数据不是数组格式:', records);
      this.setData({
        favoritesList: [],
        total: 0,
        hasMore: false,
        loading: false
      });
      return;
    }
    
    console.log('✅ 收藏数据是数组格式，长度:', records.length);
    console.log('收藏数据详情:', records);
    
    // 格式化收藏数据
    const formattedRecords = records.map(item => {
      console.log('正在格式化收藏项:', item);
      return {
        ...item,
        createTime: this.formatTime(item.createTime),
        // 根据类型设置不同的图标和样式
        typeIcon: this.getTypeIcon(item.type),
        typeColor: this.getTypeColor(item.type)
      };
    });
    
    console.log('格式化后的收藏数据:', formattedRecords);
    
    const newFavoritesList = this.data.page === 1 ? formattedRecords : [...this.data.favoritesList, ...formattedRecords];
    
    console.log('即将设置到页面的数据:', {
      favoritesList: newFavoritesList,
      total: total,
      hasMore: current < (size > 0 ? Math.ceil(total / size) : 1),
      loading: false
    });
    
    this.setData({
      favoritesList: newFavoritesList,
      total: total,
      hasMore: current < (size > 0 ? Math.ceil(total / size) : 1),
      loading: false
    });
    
    console.log('✅ setData完成，当前页面数据:', this.data.favoritesList);
  },


  /**
   * 加载更多收藏
   */
  async loadMoreFavorites() {
    this.setData({
      page: this.data.page + 1
    });
    await this.loadFavorites();
  },

  /**
   * 切换标签页
   */
  onTabChange(e) {
    const index = e.detail.index;
    this.setData({
      activeTab: index,
      favoritesList: [],
      page: 1,
      hasMore: true
    });
    this.loadFavorites();
  },

  /**
   * 点击收藏项
   */
  onFavoriteItemTap(e) {
    const { item } = e.currentTarget.dataset;
    
    if (this.data.deleteMode) {
      // 删除模式下选择/取消选择
      this.toggleSelectItem(item.id);
      return;
    }
    
    // 根据类型跳转到对应页面
    this.navigateToContent(item);
  },

  /**
   * 导航到内容详情页
   */
  navigateToContent(item) {
    if (item.type === 'example') {
      // 跳转到系统示例图详情页
      wx.navigateTo({
        url: `/pages/example-detail/example-detail?id=${item.contentId}`
      });
    } else if (item.type === 'user_work') {
      // 跳转到用户作品详情页
      wx.navigateTo({
        url: `/pages/user-work-detail/user-work-detail?id=${item.contentId}`
      });
    } else if (item.type === 'image') {
      // 兼容旧的图片类型，默认跳转到示例图详情页
      wx.navigateTo({
        url: `/pages/example-detail/example-detail?id=${item.contentId}`
      });
    } else {
      wx.showToast({
        title: '暂不支持此类型',
        icon: 'none'
      });
    }
  },

  /**
   * 长按收藏项
   */
  onFavoriteItemLongPress(e) {
    const { item } = e.currentTarget.dataset;
    
    wx.showActionSheet({
      itemList: ['取消收藏', '分享'],
      success: (res) => {
        if (res.tapIndex === 0) {
          this.removeFavoriteItem(item);
        } else if (res.tapIndex === 1) {
          this.shareFavoriteItem(item);
        }
      }
    });
  },

  /**
   * 进入删除模式
   */
  enterDeleteMode() {
    this.setData({
      deleteMode: true,
      selectedIds: []
    });
  },

  /**
   * 退出删除模式
   */
  exitDeleteMode() {
    this.setData({
      deleteMode: false,
      selectedIds: []
    });
  },

  /**
   * 切换选择项
   */
  toggleSelectItem(id) {
    const selectedIds = [...this.data.selectedIds];
    const index = selectedIds.indexOf(id);
    
    if (index > -1) {
      selectedIds.splice(index, 1);
    } else {
      selectedIds.push(id);
    }
    
    this.setData({ selectedIds });
  },

  /**
   * 全选/取消全选
   */
  toggleSelectAll() {
    const allSelected = this.data.selectedIds.length === this.data.favoritesList.length;
    
    this.setData({
      selectedIds: allSelected ? [] : this.data.favoritesList.map(item => item.id)
    });
  },

  /**
   * 批量删除收藏
   */
  async batchDeleteFavorites() {
    if (this.data.selectedIds.length === 0) {
      wx.showToast({
        title: '请选择要删除的收藏',
        icon: 'none'
      });
      return;
    }
    
    const result = await wx.showModal({
      title: '确认删除',
      content: `确定要删除选中的 ${this.data.selectedIds.length} 个收藏吗？`
    });
    
    if (!result.confirm) return;
    
    try {
      wx.showLoading({ title: '删除中...' });
      
      // 批量删除
      const deletePromises = this.data.selectedIds.map(id => 
        api.removeFavorite(id)
      );
      
      await Promise.all(deletePromises);
      
      wx.hideLoading();
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
      // 退出删除模式并刷新列表
      this.exitDeleteMode();
      this.refreshFavorites();
      
    } catch (error) {
      wx.hideLoading();
      console.error('批量删除收藏失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  /**
   * 删除单个收藏
   */
  async removeFavoriteItem(item) {
    const result = await wx.showModal({
      title: '确认删除',
      content: '确定要取消收藏这个内容吗？'
    });
    
    if (!result.confirm) return;
    
    try {
      wx.showLoading({ title: '删除中...' });
      
      await api.removeFavorite(item.id);
      
      wx.hideLoading();
      wx.showToast({
        title: '取消收藏成功',
        icon: 'success'
      });
      
      // 从列表中移除
      const favoritesList = this.data.favoritesList.filter(fav => fav.id !== item.id);
      this.setData({
        favoritesList,
        total: this.data.total - 1
      });
      
    } catch (error) {
      wx.hideLoading();
      console.error('删除收藏失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  /**
   * 分享收藏项
   */
  shareFavoriteItem(item) {
    // TODO: 实现分享功能
    wx.showToast({
      title: '分享功能开发中',
      icon: 'none'
    });
  },

  /**
   * 导航到发现页面
   */
  navigateToExplore() {
    wx.switchTab({
      url: '/pages/ai-image/ai-image'
    });
  },

  /**
   * 格式化时间
   */
  formatTime(timeStr) {
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now - date;
    
    const minute = 60 * 1000;
    const hour = minute * 60;
    const day = hour * 24;
    
    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else if (diff < day * 30) {
      return Math.floor(diff / day) + '天前';
    } else {
      return date.toLocaleDateString();
    }
  },

  /**
   * 获取类型图标
   */
  getTypeIcon(type) {
    const iconMap = {
      'user_work': 'photo-o',     // 用户作品
      'example': 'star-o',        // 示例图
      'image': 'photo-o',         // 图片 (兼容)
      'default': 'bookmark-o'     // 默认
    };
    return iconMap[type] || iconMap['default'];
  },

  /**
   * 获取类型颜色
   */
  getTypeColor(type) {
    const colorMap = {
      'user_work': '#4ecdc4',     // 用户作品 - 青色
      'example': '#ff9500',       // 示例图 - 橙色
      'image': '#ff6b6b',         // 图片 - 红色 (兼容)
      'default': '#999'           // 默认 - 灰色
    };
    return colorMap[type] || colorMap['default'];
  }
});
